<template>
  <div class="businessList">
    <NewCard title="商务" :isright="true" :border="false">
      <template #right>
        <ComForm
          title="搜索"
          @EventOnsubmit="searchRefFn"
          :list="comForm"
        ></ComForm>
      </template>
      <!-- 表格 -->
      <el-table
        :data="ManagerList"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="商务姓名">
          <template slot-scope="scope">
            <!-- <p>{{ scope.row.name }}</p> -->
            <p
              v-if="!!scope.row.isName"
              @dblclick="openEditWorkMail(scope.row, 'name')"
            >
              {{ scope.row.name }}
            </p>
            <el-input
              autofocus
              @blur="editWorkMail(scope.row, 'name')"
              v-else
              placeholder="姓名"
              v-model="scope.row.name"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机号">
          <template slot-scope="scope">
            <p>{{ scope.row.phonenumber }}</p>
          </template>
        </el-table-column>
        
        <!-- 上级 -->
        <el-table-column prop="higherLevel" label="上级">
          <template slot-scope="scope">

            <!-- <el-dropdown
              @command="
                (item) => {
                  editHigherLevelNameFn(item, scope.row, true);
                }
              "
              trigger="click"
              v-hasPermi="['work:commercialManager:edit']"
            >
              <span class="el-dropdown-link">
                {{ getHigherLevelName(scope.row.higherLevel, scope) || "--"
                }}<i class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :command="item"
                  v-for="item in ManagerListSuperiorFiter(
                    ManagerListFiter,
                    scope.row
                  )"
                  :key="item.id"
                  >{{ item.name }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown> -->

            <!-- 上级选择框 -->
            <div class="selsect-box">
              <p>{{scope.row.higherLevelName ? scope.row.higherLevelName : '--'}} <i class="el-icon-caret-bottom"></i></p>
              <el-select v-model="scope.row.higherLevel" placeholder="--" v-loadmore="superiorMore" @change="(item) => {
                editHigherLevelNameFn(item, scope.row, true);
              }"
              v-hasPermi="['work:commercialManager:edit']">
                <el-option
                  v-for="(item,index) in personnels"
                  :key="index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <!-- 上级选择框 end -->

          </template>
        </el-table-column>
        <!-- 上上级 -->
        <el-table-column prop="supervisorId" label="上上级">
          <template slot-scope="scope">

            <!-- <el-dropdown
              @command="
                (item) => {
                  editHigherLevelNameFn(item, scope.row);
                }
              "
              trigger="click"
              v-hasPermi="['work:commercialManager:edit']"
            >
              <span class="el-dropdown-link">
                {{ getHigherLevelName(scope.row.supervisorId) || "--"
                }}<i class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :command="item"
                  v-for="item in ManagerListLeaderFiter(
                    ManagerListFiter,
                    scope.row
                  )"
                  :key="item.id"
                  >{{ item.name }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown> -->

            <!-- 上上级选择框 -->
            <div class="selsect-box">
              <p>{{scope.row.supervisorName ? scope.row.supervisorName : '--'}} <i class="el-icon-caret-bottom"></i></p>
              <el-select v-model="scope.row.supervisorId" placeholder="--" v-loadmore="superiorMore" @change="(item) => {
                editHigherLevelNameFn(item, scope.row);
              }"
              v-hasPermi="['work:commercialManager:edit']">
                <el-option
                  v-for="(item,index) in personnels"
                  :key="index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <!-- 上上级选择框 end -->

          </template>
        </el-table-column>

        <!-- <el-table-column prop="workMail" label="邮箱" width='180' show-overflow-tooltip>
          <template slot-scope="scope">
            <p
              v-if="!!scope.row.isWorkMailEdit"
              @dblclick="openEditWorkMail(scope.row, 'workMail')"
            >
              {{ scope.row.workMail }}
            </p>
            <el-input
              autofocus
              @blur="editWorkMail(scope.row, 'workMail')"
              v-else
              placeholder="邮箱"
              v-model="scope.row.workMail"
              v-hasPermi="['work:commercialManager:edit']"
            ></el-input>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="amount" width="130" label="邮箱密钥">
          <template slot-scope="scope">
            <p
              v-if="!!scope.row.isMailPwd"
              @dblclick="openEditWorkMail(scope.row, 'mailPwd')"
            >
              **********
            </p>
            <el-input
              autofocus
              @blur="editWorkMail(scope.row, 'mailPwd')"
              v-else
              placeholder="密钥"
              v-model="scope.row.mailPwd"
              v-hasPermi="['work:commercialManager:edit']"
            ></el-input>
          </template>
        </el-table-column> -->
        <el-table-column prop="userCount" width="80" label="客户量">
          <template slot-scope="scope">
            <p>{{ scope.row.userCount }}</p>
          </template>
        </el-table-column>
        <el-table-column width="60" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#f87a23" active-value="0" inactive-value="1" @change="changeSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>

      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageing.total"
        >
        </el-pagination>
      </div>

      <div class="bottomBtn" v-hasPermi="['work:commercialManager:add']">
        <el-button
          v-if="buttonVissible"
          class="button-new-tag"
          size="medium"
          @click="showButton"
          >+ 添加商务</el-button
        >
        <div v-else class="inputBox">
          <!-- <el-input v-model="addObj.name" placeholder="请输入名称"></el-input> -->
          <el-input
            v-model="addObj.phonenumber"
            placeholder="请输入手机号"
          ></el-input>
        </div>
        <div class="buttonBox">
          <el-button round type="primary" @click="addBusiness">确认</el-button>
          <el-button round @click="addReset">取消</el-button>
        </div>

        <!-- <el-button @click="clickDirector" v-if="directorBtnShow"
          >+添加商务专员
        </el-button>
        <el-input
          v-model="directorBtnValue"
          v-else
          @blur="directorBtnShow = true"
          @keyup.enter.native="addDirector"
          ref="bottBtn"
        >
        </el-input> -->
      </div>
    </NewCard>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import ComForm from "@/wss/components/comForm.vue";
import {
  getCommercialManagerApi,
  getCommercialManageraddApi,
  getCommercialManagerEditApi,
} from "@/wss/newApi_3-24/work/commercialManager.js";
const arr = [null, "", undefined];
export default {
  name: "BusinessList",
  props: {
    organizationId: {
      type: String,
      default: null,
    },
  },
  components: { NewCard, ComForm },
  data() {
    return {
      pageing: { pageNum: 1, pageSize: 10, total: 10 },

      personing: { pageNum: 1, pageSize: 10, total: 0 },//人员的分页
      personnels:[],//渠道人员列表，显示在上级和上上级那里
      personnelValue: '',//选择的值

      // 是否显示添加商务按钮
      buttonVissible: true,
      // 添加商务参数
      addObj: {
        organizationId: "",
        // name: "",
        phonenumber: "",
        //类型 1商务 2渠道
        type: "1",
      },
      // 表单配置
      comForm: {
        modes: [
          {
            formType: "input",
            placeholder: "商务姓名",
            mode: "name",
          },
          {
            mode: "phonenumber",
            formType: "input",
            placeholder: "手机号",
          },
        ],
      },
      editObje: {
        workMail: "",
        mailPwd: "",
      },

      superiorList: [
        {
          label: "axi",
          value: "axi",
        },
      ],
      // 商务经理数据
      managerList: [
        {
          name: "毛不易",
          phone: "138 0013 8000",
          clientNum: "10",
          credit: "1000",
        },
        {
          name: "张韶涵",
          phone: "138 0013 8000",
          clientNum: "2",
          credit: "2000",
        },
        {
          name: "任嘉伦",
          phone: "138 0013 8000",
          clientNum: "12",
          credit: "500",
        },
        {
          name: "关晓彤",
          phone: "138 0013 8000",
          clientNum: "16",
          credit: "3500",
        },
      ],

      directorBtnShow: true, //商务总监底部按钮
      directorBtnValue: "", //商务总监底部输入值

      managerBtnShow: true, //商务经理底部按钮
      managerBtnValue: "", //商务经理底部输入值
      // 商务列表
      ManagerList: [],
      ManagerListFiter: [],
      // 查询的数据条件
      searchFrom:{
        name: '',
        phonenumber: '',
      },
    };
  },
  watch:{
    // 监听organizationId，变化就发请求
    organizationId(newValue,oldValue){
      this.personing = { pageNum: 1, pageSize: 10, total: 10 }
      this.personnels = []
      this.getCommercialManagerFn(this.organizationId) //表格数据
      this.getpersonListFn() //渠道人员列表，显示在上级和上上级那里
    },
  },
  computed: {
    // 获取上级和上上级名字
    getHigherLevelName() {
      return (id, item) => {
        console.log(item);
        return this.ManagerListFiter.find((item) => item.id == id)?.name;
      };
    },

    //过滤上级数组，要求数组中不可以有自己
    ManagerListSuperiorFiter() {
      // return (list, row) => list.filter((item) => item.id != row.id);
      return (list, row) => list.filter((item) => item);
    },
    //过滤上上级数组，要求数组中不可以有自己(目前没有使用到)
    ManagerListLeaderFiter() {
      // return (list, row) => list.filter((item) => {return item.id != row.id});
      return (list, row) =>
        list.filter((item) => {
          return item;
        });
    },
  },
  mounted() {
    this.personing = { pageNum: 1, pageSize: 10, total: 10 }
    this.personnels = []
    this.getpersonListFn() //渠道人员列表，显示在上级和上上级那里
  },
  // created() {},
  methods: {
    showButton() {
      this.buttonVissible = false;
    },
    // 添加商务
    addReset() {
      this.addObj = {
        // name: "",
        organizationId: "",
        phonenumber: "",
        type: 1,
      };
      this.buttonVissible = true;
    },
    async addBusiness() {
      const addObj = this.addObj;
      if (!/^1[3456789]\d{9}$/.test(addObj.phonenumber)) {
        this.$message({
          type: "warning",
          message: "手机号不合法",
        });
        return;
      }
      // if (addObj.name == "") {
      //   this.$message({
      //     message: "名字不可为空",
      //     type: "warning",
      //   });
      //   return;
      // }
      // 获取组织id
      addObj.organizationId = this.organizationId;
      let { code, msg } = await getCommercialManageraddApi(addObj);

      if (code != 200) return;
      // 清空
      this.addReset();
      this.getCommercialManagerFn(this.organizationId);//表格数据
      // 重置数据
      this.personing = { pageNum: 1, pageSize: 10, total: 10 }
      this.personnels = []
      this.getpersonListFn() //渠道人员列表，显示在上级和上上级那里
      // this.getCommercialManagerFn();

      this.$message({
        message: msg,
        type: "success",
      });
    },

    // 查询函数
    inqiureFn([{ name = "" }, { phonenumber = "" }]) {
      const ManagerList = this.ManagerListFiter;
      this.ManagerList = ManagerList.filter((item) => {
        item.isWorkMailEdit = arr.includes(item.workMail) ? false : true;
        item.isMailPwd = arr.includes(item.mailPwd) ? false : true;
        item.isName = arr.includes(item.name) ? false : true;
        return (
          item?.name?.includes(name) && item?.phonenumber?.includes(phonenumber)
        );
      });
    },

    // 查询商务回调
    searchRefFn([{ name = "" }, { phonenumber = "" }]){
      this.searchFrom.name = name
      this.searchFrom.phonenumber = phonenumber
      this.getCommercialManagerFn(this.organizationId) //查询接口
    },

    // 显示邮箱编辑输入框
    openEditWorkMail(row, attr) {
      switch (attr) {
        case "name":
          this.$set(row, "isName", false);
          break;
        case "mailPwd":
          this.$set(row, "isMailPwd", false);
          break;
        case "workMail":
          this.$set(row, "isWorkMailEdit", false);
          break;
      }
    },

    // 修改邮箱
    async editWorkMail(row, attr) {
      switch (attr) {
        case "name":
          if (arr.includes(row.name)) return;
          this.$set(row, "isName", true);
          break;
        case "mailPwd":
          if (arr.includes(row.mailPwd)) return;
          this.$set(row, "isMailPwd", true);
          break;
        case "workMail":
          if (arr.includes(row.workMail)) return;
          this.$set(row, "isWorkMailEdit", true);
          break;
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },

    // 点击状态关闭或者开启
    async changeSwitch(row){
      if(row.userCount && Number(row.userCount) > 0){
        row.status = "0"
        this.$message({type: "warning",message: '该商务下有捆绑用户，请把用户重新分配后再操作',});
        return
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },

    // 修改上级
    async editHigherLevelNameFn(item, row, isHigherLevel) {
      // row.higherLevelName = item.name;
      // 上级修改
      let id = this.personnelValue
      // 找到这个item对应的name
      let obj = this.personnels.find(k=>{
        return k.id == item
      })
      if (isHigherLevel) {
        this.$set(row, "higherLevel", item);
        this.$set(row, "higherLevelName", obj.name);
        // row.higherLevel = item.id;
      } else {
        // 上上级修改
        // row.supervisorId = item.id;
        this.$set(row, "supervisorId", item);
        this.$set(row, "supervisorName", obj.name);
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg,
      });
    },

    // 修改上上级
    editSupervisorNameFn() {},

    // 获取所有商务列表
    async getCommercialManagerFn(organizationId) {
       const {pageNum,pageSize}=this.pageing
      let { code, rows,total } = await getCommercialManagerApi({
        organizationId,
        pageNum,
        pageSize,
        name: this.searchFrom.name,
        phonenumber: this.searchFrom.phonenumber
      });
      if (code != 200) return;
      const ManagerList = JSON.parse(JSON.stringify(rows));
      this.pageing.total=total
      this.ManagerList = ManagerList.map((item) => {
        item.isWorkMailEdit = arr.includes(item.workMail) ? false : true;
        item.isMailPwd = arr.includes(item.mailPwd) ? false : true;
        item.isName = arr.includes(item.name) ? false : true;

        return item;
      });
      this.ManagerListFiter = JSON.parse(JSON.stringify(rows));
      // console.log(this.ManagerList, "这段时间");
    },

    // 获取所有人员列表 用在上级和上上级那里
    async getpersonListFn(){
      let {pageNum,pageSize}=this.personing
      let organizationId = this.organizationId
      let { code, rows, total } = await getCommercialManagerApi({
        organizationId,
        pageNum,
        pageSize
      });
      this.personing.total=total
      const channelList = JSON.parse(JSON.stringify(rows));
      
      channelList.forEach(item=>{
        this.personnels.push({
          name: item.name,
          id: item.id,
        })
      })
    },

    // 选择上级和上上级 滚动到底部的时候
    superiorMore(){
      if(this.personnels.length >= this.personing.total) return
      this.personing.pageNum ++
      this.getpersonListFn() // 获取所有人员列表 用在上级和上上级那里
    },

    // 点击添加渠道
    clickDirector() {
      //显示输入框
      this.directorBtnShow = false;
      //输入框自动获取焦点
      this.$nextTick(() => {
        this.$refs.bottBtn.focus();
      });
    },

    // 点击添加渠道
    clickManager() {
      //显示输入框
      this.managerBtnShow = false;
      //输入框自动获取焦点
      this.$nextTick(() => {
        this.$refs.bottBtn.focus();
      });
    },
    //输入框按回车的回调
    addManager() {
      if (this.managerBtnValue) {
        //隐藏输入框
        this.managerBtnShow = true;
        this.managerBtnValue = "";
      } else {
        this.$message({ type: "warning", message: "请输入商务经理" });
      }
    },

    // 表格总计行的规则 ****************
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 4) {
          sums[index] = "--";
          return;
        }
        if (["higherLevel", "supervisorId"].includes(column.property)) {
          sums[index] = "--";
          return;
        }
        const values = data.map((item) => {
          return Number(item[column.property]);
        });

        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = "--";
        }
        // if (index === 3) {
        //   sums[index] = this.$options.filters["sumFilters"](sums[index]);
        //   return;
        // }
      });

      return sums;
    },
    // 表格总计行的规则 **************** end
    handleCurrentChange(pageNum) {
      this.pageing.pageNum = pageNum;
      this.getCommercialManagerFn(this.organizationId);
    },
    // 页容量发生改变
    handleSizeChange(pageSize) {
      this.pageing.pageSize = pageSize;
      this.getCommercialManagerFn(this.organizationId);
    },
  },
};
</script>

<style scoped lang="scss">
.businessList {
  height: 100%;
}
.businessList >>> .el-card__body > div {
  overflow-x: initial !important;
}
.businessList >>> .el-card__body > div .el-card__body > div {
  overflow-y: auto !important;
}
::v-deep .el-form .el-form-item__content .el-input.el-input--medium {
  width: 100px !important;
}

.businessList .el-row {
  height: 100%;
}

/* 添加材料 */
.bottomBtn {
  background-color: #f6f9f8;
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  left: 0;
  padding: 9px 10px;
  width: 100%;
  border-top: 1px solid #ecedf0;
  z-index: 9;
  .inputBox {
    // flex: 1;
    display: flex;
  }
  .buttonBox {

    ::v-deep .el-button--primary {
      background-color: #f87a23;
      border-color: #f87a23;
      color: #ffffff;
      width: 90px;
      // height: 40px;
      line-height: 34px;
      padding: 0;
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
    }
    ::v-deep .el-button--default {
      background-color: #ffffff;
      width: 90px;
      // height: 40px;
      line-height: 34px;
      padding: 0;
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #606e84;
    }
  }
}

.selsect-box{
  position: relative;
}
.selsect-box>p{
  position: relative;
}
.selsect-box .el-select{
  position: absolute;
  top: 0;
  z-index: 9;
  opacity: 0;
}

//分页
.pagination{
  text-align: center;
  margin-bottom: 70px;
}

::v-deep .el-table .el-dropdown-link {
  color: unset;
}
.bottomBtn .el-button {
  width: 100%;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  line-height: 25px;
  color: #606e84;
}
.bottomBtn .el-input {
  width: 100%;
  margin-right: 10px;
}
::v-deep .bottomBtn .el-input .el-input__inner {
  height: 36px;
  line-height: 36px;
  // border-top: 1px solid #ecedf0;
  // background-color: #f8f8f8;
  // text-align: center;
}
.button-new-tag {
  position: absolute;
  bottom: 0;
  left: 0;
  border: 0;
  z-index: 2;
  display: block;
  width: 100%;
  font-size: 16px;
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-top: 1px solid #e6ebf5;
}
.element {
  width: 100%;
  height: 72px;
  box-sizing: border-box;
  padding-top: 16px;
  overflow-x: scroll; /* 设置溢出滚动 */
  white-space: nowrap;
  overflow-y: hidden;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
}
.element::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
::v-deep .el-table__body-wrapper {
  overflow-x: hidden;
  overflow: scroll !important;
}
::v-deep .el-table {
}
</style>